//
//  WBRefreshControl.swift
//  自定义下拉刷新控件
//
//  Created by 韩菲菲 on 16/8/15.
//  Copyright © 2016年 韩菲菲. All rights reserved.
//

import UIKit

enum WBRefreshControlState: Int{
    
    case Normal
    case Pulling
    case Refreshing
    
}

private let WBRefreshControlH:CGFloat = 50


class WBRefreshControl: UIControl {
    
    var scrollView : UIScrollView?
    
    //记录状态
    var wbState:WBRefreshControlState = .Normal{
        //当状态改变的时候会走这个方法 因为会给这个属性重新赋值
        didSet{
            
            switch wbState{
            case .Normal:
                //修改显示信息的文字
                messageLabel.text = "正常"
                //箭头恢复原状
                UIView.animateWithDuration(0.5, animations: {
                    
                    self.pullImageView.transform = CGAffineTransformIdentity
                    
                })
                
                //如果上个状态是下拉刷新
                if oldValue == .Refreshing{
                
                    UIView.animateWithDuration(0.5, animations: {
                        
                        self.scrollView?.contentInset.top -= WBRefreshControlH
                        
                        }, completion: { (_) in
                            
                            //结束菊花动画
                            self.activityView.stopAnimating()
                            //显示箭头图片
                            self.pullImageView.hidden = false
                            
                    })
                }
                
            case .Pulling:
                //下拉状态
                messageLabel.text = "下拉中"
                //要给箭头转变方向
                //设置动画效果
                UIView.animateWithDuration(0.5, animations: {
                    
                    self.pullImageView.transform = CGAffineTransformMakeRotation(CGFloat(-3 * M_PI))
                    
                })
                
            default:
                //刷新状态
                messageLabel.text = "刷新中"
                
                UIView.animateWithDuration(0.5, animations: {
                    
                    self.scrollView?.contentInset.top += WBRefreshControlH
                    
                    }, completion: { (_) in
                        
                        //隐藏箭头图片
                        self.pullImageView.hidden = true
                        //开启动画
                        self.activityView.startAnimating()
                        
                        //告诉外界刷新 当外界为当前控制器addtarget的时候 外面的控制器就会接收到通知
                        self.sendActionsForControlEvents(.ValueChanged)
                        
                })

            }
            
        }
        
    }
    
    //给外界提供一个方法 结束刷新
    func endRefreshing(){
    
        wbState = .Normal
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, -WBRefreshControlH, ScreenW, WBRefreshControlH))
        
        setupUI()
    }
    
    //设置UI
    func setupUI() {
        
        backgroundColor = UIColor.orangeColor()
        
        //添加控件
        addSubview(messageLabel)
        addSubview(pullImageView)
        addSubview(activityView)
        
        //设置约束
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item:messageLabel , attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        pullImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item:pullImageView , attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        activityView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item:activityView , attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: activityView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
    }
    
    // 监听tableview的移动
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        //获取到控件 通过KVO监听他得偏移距离
        guard let scrollView = newSuperview as? UIScrollView else{
            
            return
        }
        
        self.scrollView = scrollView
        
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
    }
    
    //监听方法的实现
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //记录tableview的偏移量
        let contentOffsetY = self.scrollView!.contentOffset.y
        
        let contentInsetTop = self.scrollView!.contentInset.top
        
        //判断手指是否在拖动的属性
        if scrollView!.dragging {
            //代表手指在拖动
            if contentOffsetY > -WBRefreshControlH-contentInsetTop && wbState == .Pulling{
          
                wbState = .Normal
            }else if contentOffsetY <= -WBRefreshControlH-contentInsetTop && wbState == .Normal
            {
         
                wbState = .Pulling
            }
        }else{
            
            //表示松开手指了
            //如果上个状态是下拉中 我松开手指以后要去刷新
            //如果上个状态是正常，我松开手指以后就不去刷新
            if wbState == .Pulling{
                
              
                wbState = .Refreshing
            }
            
        }
    }
    
    //移除KVO监听者
    deinit {
        
        self.scrollView!.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //懒加载刷新菊花
    private lazy var activityView:UIActivityIndicatorView = UIActivityIndicatorView()
    
    //懒加载显示Label
    private lazy var messageLabel:UILabel = {
        
        let label = UILabel()
        
        label.text = "正常"
        label.font = UIFont.systemFontOfSize(15)
        label.textColor = UIColor.whiteColor()
        
        
        return label
    }()
    
    //懒加载显示箭头
    private lazy var pullImageView: UIImageView = {
        
        let imageView = UIImageView()
        imageView.image = UIImage(named: "tableview_pull_refresh")
        
        return imageView
        
    }()
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
}
